﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Text;
using System.Data.OleDb;
using FluentData;
using HtmlAgilityPack;
using TaoBaoKe.Common;
using System.Net;
using System.Globalization;
namespace htmlTBK
{
    public class TbkHttpHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return false; }
        }
        /// <summary>
        ///  /key/item/00001/1
        ///  /key/shop/00001/2
        ///  /key/search/keyword/1
        ///  /key/source/base64/.1.72.js
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            //建议
            string template_suggest = "<li><a href=\"{0}\" target=\"_blank\">{1}</a></li>";
            //数据
            string template_item = " <li><a data-itemid=\"{7}\" href='{0}' rel='nofollow' target=\"_blank\"><img src='{1}' alt='点击查看'/></a>"
                + "<h3><a data-itemid=\"{7}\" href='{0}' rel='nofollow'  title='' target=\"_blank\">{2}</a></h3><em >{3}</em><span style='clear:right;'>{4}</span>"
                + "<em style='clear:both;background:none;padding-left:0; color:black;font-size:12px;font-weight:normal;'>{5}</em><span>{6}</span></li>";
            //关联数据
            string template_relate = "<li><a href=\"{0}\" target=\"_blank\">{1}</a></li>";
            // 路由  /key/w/0001/10 
            //key=>项目 w=>关键字拼音 0001=>关键字id  10=>页码
            string template = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><title>{0}-购物导航</title><meta name=\"keywords\" content=\"{0}\"/><meta name=\"description\" content=\"{0},提供最优质的{0}服务,网上购买{0}价格|排行|怎么样|哪种好|包邮,如何|去哪里|怎么能{0}\"/>{7}{8}</head><body><div class=\"all\"><div class=\"t1\"><div class='mtitle' ><strong>您好，欢迎来到2013{0}团购排行榜,{0},网上购买{0}_{0}怎么样</strong></div></div><div class=\"t2\"><div class=\"logo\"> </div><div class=\"title\"> <h1>{0}</h1> </div></div><div class=\"menu\"> <a href=\"{5}\">网站首页</a><script>echo(link);</script><a href=\"{5}\" class=\"more\">更多</a> <input type='text' id='keyword' /><input type='button' value='搜索' onclick='search();' /></div><script>echo(tui);</script><div class=\"xiangguan about\"><ul><li><b>您是否在找:</b></li>{1}</ul></div><div class=\"list cb db\" id ='list-content'><div class=\"mt\"><strong>{0},{0}哪种好,网上购买{0},网购{0}</strong></div><ul> {2}</ul><div class=\"mt\"><ul id=\"page\"><li>页码:</li>{3}</ul></div></div><div class=\"xiangguan cb db\"><h4>相关搜索</h4><ul>{4}</ul></div><div class=\"dibu\"><p>免责声明：<a href=\"{0}\"></a>信息收集于淘宝网，淘宝商城以及京东商城，拍拍网，易讯网等购物网站，欢迎大家对网站内容侵犯版权等不合法和不健康行为进行监督和举报。 </p><p>Copyright © 2001-2013 <a href=\"{6}\">正品{0}官网</a><script type=\"text/javascript\">echo(tj);</script></p></div></div>{9}</body></html>";
            string css = "<style type=\"text/css\"> *{margin:0px;padding:0px;}body{font-family:\"微软雅黑\",\"宋体\";margin:0px;font-size:12px;background:url(/images/bg.gif) repeat-x}ul,.top{height:100%;overflow:hidden;}li{list-style-type:none;}img{border:none;}.about{border:1px solid  rgba(255,0,0,0.19);margin-top:13px;margin-bottom:8px;}.cb{border:1px solid #aedef2;}.wo{height:2400px;overflow:hidden;}.db{margin-bottom:6px;}a{color:#075db3;text-decoration:none;}a:hover{color:red;text-decoration:underline;}input{vertical-align:middle;}h4{font-size:12px;color:#1974c8;padding:4px 0 4px 15px;position:relative;height:16px;overflow:hidden;background:#eef5fd;border-bottom:1px solid #aedef2;}.all{width:1265px;margin:0 auto;overflow:hidden;}.topleft{width:320px;overflow:hidden;margin-top:25px;}.logo{width:100%;height:70px;overflow:hidden;}.shu{float:left;}.hen{float:right;}.topright{width:640px;overflow:hidden;margin-top:35px;margin-bottom:15px;}.daohang{BORDER-LEFT:#780b01 1px solid;WIDTH:958px;BACKGROUND:url(/images/t2.gif) repeat-x 0px 0px;HEIGHT:32px;CLEAR:both;BORDER-RIGHT:#780b01 1px solid}.daohang A{TEXT-ALIGN:center;LINE-HEIGHT:32px;WIDTH:72px;DISPLAY:inline;BACKGROUND:url(/images/t2.gif) 0px 0px;FLOAT:left;HEIGHT:32px;COLOR:#fff}.daohang A:hover,.menu A.this{BACKGROUND:url(/images/t2.gif) 0px -32px;COLOR:#fff000;FONT-SIZE:13px;FONT-WEIGHT:bolder;TEXT-DECORATION:none}.fenye{text-align:center;padding:8px 0;}.fenye a{display:inline-block;padding:2px 6px;border:1px solid #eee;margin-left:6px;margin-right:6px;}.current{display:inline-block;padding:2px 6px;border:1px solid #eee;BACKGROUND:#f6f2f2;}.mt STRONG{font-size:12px;COLOR:#f00}.mt h1{font-size:12px;COLOR:#f00}.mt{PADDING:0px 15px;LINE-HEIGHT:27px;HEIGHT:27px;BORDER:#e2e2e2 1px solid;BACKGROUND:#f6f2f2;margin:10px 10px 10px 18px;overflow:hidden;text-align:center;}.xiangguan ul{padding:3px 0 10px 12px;}.xiangguan ul li{overflow:hidden;float:left;display:inline;margin:3px 10px 0 0;white-space:nowrap;text-overflow:ellipsis;height:26px;line-height:26px;}.dibu{text-align:center;line-height:1.8;padding:5px 0 10px 0;}.dibu a{color:#000000;}.neirong{clear:both;width:960px;margin:0 auto;color:#333333;margin-top:3px;margin-bottom:9px;height:100%;overflow:hidden;}.neirong1{float:left;width:308px;height:308px;border:1px solid #e5e5e5;padding:2px;margin-left:15px;}.neirong1 img{width:308px;height:308px}.neirong2{overflow:hidden;float:left;width:418px;height:310px;}.neirong2 ul li{width:100%;float:left;text-align:left;padding-left:18px;line-height:39px;height:39px;color:#000000;}.neirong2 ul li span{font-size:22px;color:#FF3300;}.neirong3{float:left;width:185px;height:256px;padding:1px;margin-left:5px;border:1px solid #e5e5e5;}.xingyong{LINE-HEIGHT:24px;MARGIN:0px;WIDTH:180px;BACKGROUND:#fff;OVERFLOW:hidden}.xingyong .tupian{MARGIN:5px;HEIGHT:80px}.xingyong .tupian IMG{WIDTH:80px;FLOAT:left;HEIGHT:80px;MARGIN-RIGHT:5px}.xingyong .ty{MIN-HEIGHT:50px;PADDING-LEFT:5px}.xingyong .ty A{TEXT-DECORATION:underline}.xingyong .ty UL{LIST-STYLE-TYPE:none;MARGIN-BOTTOM:10px;LIST-STYLE-IMAGE:none;_padding-bottom:3px}.xingyong .ty LI{LINE-HEIGHT:15px;MARGIN-BOTTOM:5px}.____list___{height:2220px;overflow:hidden;}.list ul{padding:0 0 12px 18px;}.list ul li{width:220px;overflow:hidden; float:left;display:inline;margin:12px 26px 20px 0;BORDER-BOTTOM:#e5e5e5 1px solid;}.list ul li img{padding:5px;border:1px solid #e5e5e5;display:block;height:210px;}.list ul li h3{WIDTH:210px;TEXT-OVERFLOW:ellipsis;HEIGHT:36px;COLOR:#0063dc;FONT-SIZE:12px;OVERFLOW:hidden;FONT-WEIGHT:400;margin-bottom:8px;PADDING:0px 0px 0px 5px;}.list ul li em{font-style:normal;BACKGROUND:url(http://img03.taobaocdn.com/tps/i3/T1ebamXel5XXXXXXXX-20-2400.png) no-repeat;PADDING-LEFT:16px;FONT:bold 16px Arial;BACKGROUND-POSITION:-5px -81px;COLOR:#ff2900;FLOAT:left}.list ul li span{FLOAT:right;}.tips{MARGIN-top:30px;MARGIN-left:25px;margin-bottom:20px;}.tips strong{font-size:22px;color:#FF3300;}.t1{height:26px;line-height:26px;}.mtitle strong{font-size:12px;color:#969696;line-height:25px;height:20px;}.t2{height:79px;}.t2 .logo{float:left;width:250px;height:79px;background:url(/images/t2_logo.gif) no-repeat;}.t2 .title{float:left;height:79px;}.title h1{font-size:18px;color:#FFF;line-height:79px;margin-left:5px;}.menu{clear:both;height:32px;}.menu a{float:left;width:76px;height:32px;line-height:32px;background:url(/images/t2.gif) 0px 0px;color:#FFF;text-align:center;display:inline;}.menu a:hover,.menu a.this{background:url(/images/t2.gif) 0px -32px;color:#fff000;font-weight:bolder;text-decoration:none;font-size:13px;}.menu a.more{float:left;width:39px;height:32px;line-height:32px;background:url(/images/t2.gif) 0px 0px;color:#FFF;text-align:Center;border-right:1px solid #990000;}.menu a.more:hover,.menu a.more.this{background:url(/images/t2.gif) 0px 32px;color:#fff000;font-weight:bolder;text-decoration:none;}.tr h3{text-align:right;font-size:12px;color:#CCCCCC;line-height:25px;height:20px;margin:0 5px;}#page li{list-style:none;float:left;display:block;margin:0 5px;width:auto;}.H{float:none;font-weight:bold;color:red;}</style>";
            string js = "<script type=\"text/javascript\">function search() { var key = document.getElementById('keyword').value; if (key != '') location.href = '/search/' + document.getElementById('keyword').value + '/'; else alert('请输入关键字');} function echo(str){document.write(str);}var tj=\"\";var tui='';var link='<a href=\"http://www.taobao.com/go/chn/tbk_channel/food.php?pid=mm_33315358_3478037_13082544&eventid=101865\" target=\"_blank\">食品美味</a><a href=\"http://www.taobao.com/go/chn/tbk_channel/lady.php?pid=mm_33315358_3478037_13082544&eventid=101345\" target=\"_blank\">女装频道</a><a href=\"http://www.taobao.com/go/chn/tbk_channel/digital.php?pid=mm_33315358_3478037_13082544&eventid=101332\" target=\"_blank\">数码频道</a><a href=\"http://www.taobao.com/go/chn/tbk_channel/jewelry.php?pid=mm_33315358_3478037_13082544&eventid=101331\" target=\"_blank\">饰品鞋包</a><a href=\"http://www.taobao.com/go/chn/tbk_channel/beauty.php?pid=mm_33315358_3478037_13082544&eventid=101328\" target=\"_blank\">美容护肤</a><a href=\"http://www.taobao.com/go/chn/tbk_channel/man.php?pid=mm_33315358_3478037_13082544&eventid=101330\" target=\"_blank\">男人频道</a><a href=\"http://www.taobao.com/go/chn/tbk_channel/child.php?pid=mm_33315358_3478037_13082544&eventid=102185\" target=\"_blank\">母婴频道</a><a href=\"http://www.tmall.com/go/chn/tbk_channel/tmall_new.php?pid=mm_33315358_3478037_13082544&eventid=101334\" target=\"_blank\">天猫频道</a><a href=\"http://www.taobao.com/go/chn/tbk_channel/channelcode.php?pid=mm_33315358_3478037_13082544&eventid=101329\" target=\"_blank\">综合频道</a><a href=\"http://www.taobao.com/go/chn/tbk_channel/baby.php?pid=mm_33315358_3478037_13082544&eventid=101326\" target=\"_blank\">家装频道</a><a href=\"http://www.taobao.com/go/chn/tbk_channel/trip.php?pid=mm_33315358_3478037_13082544&eventid=101829\" target=\"_blank\">机票频道</a>';"+
            "(function(win,doc){var s=doc.createElement(\"script\"),h=doc.getElementsByTagName(\"head\")[0];if(!win.alimamatk_show){s.charset=\"gbk\";s.async=true;s.src=\"http://a.alimama.cn/tkapi.js\";h.insertBefore(s,h.firstChild)};var o={pid:\"mm_33315358_4062976_13236302\",appkey:\"\",unid:\"\",rd:1};win.alimamatk_onload=win.alimamatk_onload||[];win.alimamatk_onload.push(o)})(window,document);" +
            "</script>";
            string footJs = "<script language=\"javascript\" type=\"text/javascript\" src=\"http://js.users.51.la/15924824.js\"></script><noscript><a href=\"http://www.51.la/?15924824\" target=\"_blank\"><img alt=\"&#x6211;&#x8981;&#x5566;&#x514D;&#x8D39;&#x7EDF;&#x8BA1;\" src=\"http://img.users.51.la/15924824.asp\" style=\"border:none\" /></a></noscript>";
            string key = "光盘";
            string path = context.Request.Path;
            StringBuilder sb = new StringBuilder();
            string link_suggest = "";
            string link_content = "";
            string link_pageno = "";
            string link_relate = "";
            string link_base = "/";
            string link_current = "";

            IDbContext dbContext = new DbContext().ConnectionString(string.Format("Provider=Microsoft.Jet.Oledb.4.0;data source={0}", context.Server.MapPath("~/Data/data.mdb")), new AccessProvider());
            try
            {
                string[] param = path.Split(new char[] { '/' });
                string project = param[1];
                if (project.ToLower() == "index.html")
                {
                    string indexTemplate = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><title>搜索购物风向标</title>{1}{2}</head><body><div class=\"all\"><div class=\"t1\"><div class='mtitle' ><strong>欢迎来到搜索购物风向标！</strong></div></div><div class=\"t2\"><div class=\"logo\"> </div><div class=\"title\"> <h1>网友热搜风向标</h1> </div></div><div class=\"menu\"> <a href=\"http://iua8.com/\">网站首页</a><script type=\"text/javascript\">echo(link);</script><a href=\"http://iua8.com/\" class=\"more\">更多</a> <input type='text' id='keyword' /><input type='button' value='搜索' onclick='search();' /> </div><div class=\"xiangguan cb db\" style='text-align:center;margin-top:13px'><ul>{0}</ul></div><div class=\"dibu\"><p>信息收集于淘宝网，淘宝商城以及京东商城，拍拍网，易讯网等购物网站，欢迎大家对网站内容侵犯版权等不合法和不健康行为进行监督和举报。<script type=\"text/javascript\">echo(tj);</script></p></div></div></body></html>";
                    Random rnd = new Random();
                    string rndIndex = "";
                    for (int  rndi= 0;  rndi   <400 ; rndi++)
                    {
                        rndIndex += (rndi!=0?",":"") + rnd.Next(61714);
                    }
                    List<Models.tbk_KeywordBySeed> relateData = 
                        dbContext.Sql("select  top 400  * from tbk_KeywordBySeed order by rnd(kid)").QueryMany<Models.tbk_KeywordBySeed>();
                    if (relateData != null && relateData.Count > 0)
                    {
                        sb.Clear();
                        for (int relatei = 0; relatei < relateData.Count; relatei++)
                        {
                            sb.AppendFormat(template_relate, "/" + relateData[relatei].Keyword.ToPinYin() + "/" + relateData[relatei].Kid.ToString() + "/", relateData[relatei].Keyword);
                        }
                    }
                    link_relate = sb.ToString();
                    context.Response.Write(string.Format(indexTemplate,link_relate,css,js));
                    return;
                }
                string keyPinYin = param[1];
                string keyId = param[2];
                if (keyPinYin == "source")
                {
                    context.Response.StatusCode = 301;
                    context.Response.RedirectLocation = keyId.Base64Decode();
                    return;
                }
                if (keyPinYin == "search")
                {
                    key = context.Server.UrlDecode(keyId);
                }
                else
                {
                    int keyindex = 1;
                        int.TryParse(keyId,out keyindex);
                    Models.tbk_KeywordBySeed m = dbContext.Sql("select * from tbk_KeywordBySeed where Kid=" + keyindex).QuerySingle<Models.tbk_KeywordBySeed>();
                    if (m != null)
                    {
                        key = m.Keyword;
                    }
                    //过滤
                    string[] filter=new string[]{"维修","报告","怎样"};
                    foreach (var item in filter)
                    {
                        key = key.Replace(item, "");
                    }
                    
                    //相关
                    List<Models.tbk_KeywordBySeed> relateData = dbContext.Sql("select * from tbk_KeywordBySeed where Kid>" + keyindex + " and kid<" + (keyindex + 11)).QueryMany<Models.tbk_KeywordBySeed>();
                    //List<Models.tbk_KeywordBySeed> relateData = dbContext.Sql("select top 12 * from tbk_KeywordBySeed order by rnd(kid)").QueryMany<Models.tbk_KeywordBySeed>();
                    if (relateData != null && relateData.Count > 0)
                    {
                        sb.Clear();
                        for (int relatei = 0; relatei < relateData.Count; relatei++)
                        {
                            sb.AppendFormat(template_relate, "/" + relateData[relatei].Keyword.ToPinYin() + "/" + relateData[relatei].Kid.ToString() + "/", relateData[relatei].Keyword);
                        }
                    }
                    link_relate = sb.ToString();
                }
                sb.Clear();
                int pageNo = 1;
                string pageParam = "&s=0";
                if (int.TryParse(param[3], out pageNo) && pageNo > 1)
                {
                    pageParam = "&s=" + (pageNo - 1) * 40;
                }
                HtmlWeb web = new HtmlWeb();
                web.UseCookies = false;
                web.NeedParse = false;
                web.OverrideEncoding = Encoding.GetEncoding("gb2312");
                web.PreRequest += req;
                //&sort=sale-desc&tab=mall&
                HtmlDocument hd = web.Load("http://110.75.29.129/search?q=" + context.Server.UrlEncode(key) + pageParam);
                string result = hd.Text;
                result = result.Replace("\n", "").Replace("\r", "");
                MatchCollection s_mc = result.Matches("<div class=\"tb-related.*?[^>]>.*?<div\\sclass=\"bd\">(.*?)</div>");
                if (s_mc.Count > 0)
                {
                    string r_s = s_mc[0].Value;
                    s_mc = r_s.Matches("<li><a.*?>(?<s_key>.*?)<span");
                    if (s_mc.Count > 0)
                    {
                        sb.Clear();
                        for (int s_mci = 0; s_mci < s_mc.Count; s_mci++)
                        {
                            sb.AppendFormat(template_suggest, "/search/" + context.Server.UrlEncode(s_mc[s_mci].Groups["s_key"].Value) + "/1", s_mc[s_mci].Groups["s_key"].Value);
                        }
                    }
                }
                link_suggest = sb.ToString();
                MatchCollection mcc = null;
                //分页
                #region
                //mcc = result.Matches("count:'(?<page>.*?)',index");
                //if (mcc.Count > 0)
                //{
                //    sb.Clear();
                //    int total = 0;
                //    if (int.TryParse(mcc[0].Groups["page"].Value, out total))
                //    {

                //    }
                //    total = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(total / 40)));
                //    for (int pagei = pageNo - 15; pagei <= pageNo + 15; pagei++)
                //    {
                //        if (pagei < 1)
                //        {
                //            continue;
                //        }
                //        if (pagei > total)
                //        {
                //            break;
                //        }
                //        sb.AppendFormat(template_relate, "/" + project + "/" + keyPinYin + "/" + keyId + "/" + pagei, pagei == pageNo ? "<b>" + pagei + "</b>" : pagei.ToString());
                //    }
                //    sb.AppendFormat(template_relate, "#", "总计" + total + "页");
                //    link_pageno = sb.ToString();
                //}
                #endregion
                #region 匹配 bx-path="components/content-grid/"
                mcc = result.Matches("bx-path=\"components/content-grid/\"(.*?)</div>.*?<div\\sclass=\"tb-bottom\">");
                if (mcc.Count == 0)
                {
                    link_content = "no data found";
                }
                else
                {
                    result = mcc[0].Value;
                    mcc = result.Matches("<div\\sclass=\"pic\".*?[^>]>.*?<div class=\"row\\sservice-box\">");
                    sb.Clear();
                    if (mcc.Count > 0)
                    {
                        //分开每个匹配 整体匹配导致某一项不存在整个都匹配不出来
                        string url = "<p\\sclass=\"pic-box\"><a.*?href=\".*?(?<url>\\d+).*?[^>]>";
                        string img = "<img\\ssrc=\"(?<img>.*?)\"\\s/>";
                        string name = "<h3.*?<a.*?[^>]>\\s*(?<name>.*?)\\s*</a>";
                        string price = "price\">(?<price>.*?)<em>";
                        string dealing = "<div\\sclass=\"col\\sdealing\">(?<dealing>.*?)</div>";
                        string comment = "count\">.*?target=\"_blank\">(?<comment>.*?)</a>";
                        string seller = "seller\"><a.*?[^>]>(?<seller>.*?)</a>";
                        string loc = "loc\">(?<loc>.*?)</div>";
                        string pattern = "";
                        Match tempmcc = null;
                        for (int i = 0; i < mcc.Count; i++)
                        {
                            //context.Response.Write(mcc[i].Value + "<br/>\n\n\n\n\n\n\n\n\n");
                            string r = mcc[i].Value;
                            //url
                            pattern = url;
                            tempmcc = r.Match(pattern);
                            if (tempmcc.Index >= 0)
                            {
                                pattern = tempmcc.Groups["url"].Value;
                            }
                            else
                            {
                                pattern = "no data found";
                            }
                            string url_value = pattern;
                            //img
                            pattern = img;
                            tempmcc = r.Match(pattern);
                            if (tempmcc.Index >= 0)
                            {
                                pattern = tempmcc.Groups["img"].Value;
                            }
                            else
                            {
                                pattern = "no data found";
                            }
                            string img_value = pattern;
                            //name
                            pattern = name;
                            tempmcc = r.Match(pattern);
                            if (tempmcc.Index >= 0)
                            {
                                pattern = tempmcc.Groups["name"].Value;
                            }
                            else
                            {
                                pattern = "no data found";
                            }
                            string name_value = pattern;
                            //price
                            pattern = price;
                            tempmcc = r.Match(pattern);
                            if (tempmcc.Index >= 0)
                            {
                                pattern = tempmcc.Groups["price"].Value;
                            }
                            else
                            {
                                pattern = "no data found";
                            }
                            string price_value = pattern;
                            //dealing
                            pattern = dealing;
                            tempmcc = r.Match(pattern);
                            if (tempmcc.Index >= 0)
                            {
                                pattern = tempmcc.Groups["dealing"].Value;
                            }
                            else
                            {
                                pattern = "no data found";
                            }
                            string dealing_value = pattern;
                            //comment
                            pattern = comment;
                            tempmcc = r.Match(pattern);
                            if (tempmcc.Index >= 0)
                            {
                                pattern = tempmcc.Groups["comment"].Value;
                            }
                            else
                            {
                                pattern = "no data found";
                            }
                            string comment_value = pattern;
                            //seller
                            pattern = seller;
                            tempmcc = r.Match(pattern);
                            if (tempmcc.Index >= 0)
                            {
                                pattern = tempmcc.Groups["seller"].Value;
                            }
                            else
                            {
                                pattern = "no data found";
                            }
                            string seller_value = pattern;
                            //loc
                            pattern = loc;
                            tempmcc = r.Match(pattern);
                            if (tempmcc.Index >= 0)
                            {
                                pattern = tempmcc.Groups["loc"].Value;
                            }
                            else
                            {
                                pattern = "no data found";
                            }
                            string loc_value = pattern;
                            sb.AppendFormat(template_item, "#" + url_value, "/source/" + img_value.Base64Encode() + "/", name_value, price_value.Replace("￥", ""), dealing_value.Replace("最近", ""), comment_value, loc_value,url_value);
                        }
                    }


                }
                #endregion
                #region 匹配 bx-path="components/content-list/"
                //context.Response.Write(result);
                //context.Response.End();
                //return;
                mcc = result.Matches("bx-path=\"components/content-list/\".*?<div\\sclass=\"tb-bottom\">");
                if (mcc.Count == 0)
                {
                    link_content = "no data found";
                }
                else
                {
                    result = mcc[0].Value;
                    mcc = result.Matches("<div\\sclass=\"pic-box-big\">.*?<div\\sclass=\"col\\send\\sservice\">");
                    sb.Clear();
                    if (mcc.Count > 0)
                    {
                        //分开每个匹配 整体匹配导致某一项不存在整个都匹配不出来
                        string url = "<p\\sclass=\"pic-box\"><a.*?href=\".*?(?<url>\\d+?)\".*?[^>]>";
                        string img = "<img\\ssrc=\"(?<img>.*?)\"";
                        string name = "<h3.*?<a.*?[^>]>\\s*(?<name>.*?)\\s*</a>";
                        string price = "price\">(?<price>.*?)<em>";
                        string dealing = "<div\\sclass=\"col\\sdealing\">(?<dealing>.*?)</div>";
                        string comment = "count\">.*?target=\"_blank\">(?<comment>.*?)</a>";
                        string seller = "seller\"><a.*?[^>]>(?<seller>.*?)</a>";
                        string loc = "loc\">(?<loc>.*?)</div>";
                        string pattern = "";
                        Match tempmcc = null;
                        for (int i = 0; i < mcc.Count; i++)
                        {
                            //context.Response.Write(mcc[i].Value + "<br/>\n\n\n\n\n\n\n\n\n");
                            string r = mcc[i].Value;
                            //url
                            pattern = url;
                            tempmcc = r.Match(pattern);
                            if (tempmcc.Index >= 0)
                            {
                                pattern = tempmcc.Groups["url"].Value;
                            }
                            else
                            {
                                pattern = "no data found";
                            }
                            string url_value = pattern;
                            //img
                            pattern = img;
                            tempmcc = r.Match(pattern);
                            if (tempmcc.Index >= 0)
                            {
                                pattern = tempmcc.Groups["img"].Value;
                            }
                            else
                            {
                                pattern = "no data found";
                            }
                            string img_value = pattern;
                            //name
                            pattern = name;
                            tempmcc = r.Match(pattern);
                            if (tempmcc.Index >= 0)
                            {
                                pattern = tempmcc.Groups["name"].Value;
                            }
                            else
                            {
                                pattern = "no data found";
                            }
                            string name_value = pattern;
                            //price
                            pattern = price;
                            tempmcc = r.Match(pattern);
                            if (tempmcc.Index >= 0)
                            {
                                pattern = tempmcc.Groups["price"].Value;
                            }
                            else
                            {
                                pattern = "no data found";
                            }
                            string price_value = pattern;
                            //dealing
                            pattern = dealing;
                            tempmcc = r.Match(pattern);
                            if (tempmcc.Index >= 0)
                            {
                                pattern = tempmcc.Groups["dealing"].Value;
                            }
                            else
                            {
                                pattern = "no data found";
                            }
                            string dealing_value = pattern;
                            //comment
                            pattern = comment;
                            tempmcc = r.Match(pattern);
                            if (tempmcc.Index >= 0)
                            {
                                pattern = tempmcc.Groups["comment"].Value;
                            }
                            else
                            {
                                pattern = "no data found";
                            }
                            string comment_value = pattern;
                            //seller
                            pattern = seller;
                            tempmcc = r.Match(pattern);
                            if (tempmcc.Index >= 0)
                            {
                                pattern = tempmcc.Groups["seller"].Value;
                            }
                            else
                            {
                                pattern = "no data found";
                            }
                            string seller_value = pattern;
                            //loc
                            pattern = loc;
                            tempmcc = r.Match(pattern);
                            if (tempmcc.Index >= 0)
                            {
                                pattern = tempmcc.Groups["loc"].Value;
                            }
                            else
                            {
                                pattern = "no data found";
                            }
                            string loc_value = pattern;
                            sb.AppendFormat(template_item, "#" + url_value, "/source/" + img_value.Base64Encode() + "/", name_value, price_value.Replace("￥", ""), dealing_value.Replace("最近", ""), comment_value, loc_value,url_value);
                        }
                    }
                }

                #endregion

                link_content = sb.ToString();
                context.Response.AddHeader("Last-Modified", DateTime.Now.ToString("U", DateTimeFormatInfo.InvariantInfo));
                DateTime IfModifiedSince;
                if (DateTime.TryParse(context.Request.Headers.Get("If-Modified-Since"), out IfModifiedSince))
                {
                    if ((DateTime.Now - IfModifiedSince.AddHours(8)).Seconds < 60*60*10)
                    {
                        context.Response.Status = "304 Not Modified";
                        context.Response.StatusCode = 304;
                        return;
                    }
                }

                context.Response.Write(string.Format(template, key, link_suggest, link_content, link_pageno, link_relate, link_base, link_current, css, js,footJs));
            }
            catch (Exception e)
            {
                //throw e;
                context.Response.Clear();
                context.Response.StatusCode = 403;
            }
            finally
            {
                dbContext.Dispose();
            }
        }
        private bool req(System.Net.HttpWebRequest request)
        {
            request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8");
            request.Headers.Add("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
            request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
            request.Headers.Add("Origin", "http://search.taobao.com");
            request.AutomaticDecompression = DecompressionMethods.GZip;
            request.Host = "search.taobao.com";
            request.Referer = "http://search.taobao.com/search?q=%B4%F3%C5%C6%D7%D3&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=1.1000386.5803581.d4908513";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31";
            return true;
        }
    }
}